package org.yzh.scheduler.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.yzh.commons.model.APIResult;
import org.yzh.commons.model.UserPrincipal;
import org.yzh.commons.model.enums.APICodes;
import org.yzh.commons.util.JWTUtil;
import org.yzh.commons.util.NetUtils;
import org.yzh.commons.model.enums.Role;
import org.yzh.scheduler.model.vo.Token;

import java.io.IOException;
import java.net.InetAddress;
import java.time.Instant;
import java.time.temporal.ChronoUnit;

@Tag(name = "认证API")
@RestController
public class AuthController {

    @Value("${password}")
    private String password;

    @Operation(summary = "登陆")
    @PostMapping("auth/login")
    public APIResult<Token> login(@Parameter(description = "用户名", required = true) @RequestParam String username,
                                  @Parameter(description = "密码", required = true) @RequestParam String password) {
        if (!this.password.equals(password))
            return new APIResult<>(APICodes.InvalidParameter, "用户名或密码错误");

        Instant issuedAt = Instant.now();
        Instant expiresAt = issuedAt.plus(7, ChronoUnit.DAYS);
        UserPrincipal user = new UserPrincipal(1, Role.Admin, issuedAt, expiresAt);

        String token = JWTUtil.sign(user);
        return new APIResult<>(new Token(token, username, user.getRole()));
    }

    @GetMapping("/")
    public void home(HttpServletResponse response) throws IOException {
        response.sendRedirect("home.html");
    }

    @GetMapping("/ip")
    public String ip() {
        InetAddress lanAddress = NetUtils.getLocalHostLANAddress();
        return "lanAddress: " + lanAddress;
    }
}